package com.cg.springSecurity.security;

import com.google.gson.Gson;
import com.cg.springSecurity.base.ResultInfo;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //返回json数据
        ResultInfo result = null;
        Gson gson =new Gson();
        if (e instanceof AccountExpiredException) {
            //账号过期
            result = new ResultInfo<>("error" , "账号过期");
        } else if (e instanceof BadCredentialsException) {
            //密码错误
            result = new ResultInfo<>("error" , "密码错误");
        } else if (e instanceof CredentialsExpiredException) {
//            密码过期
            result = new ResultInfo<>("error" , "密码过期");
        } else if (e instanceof DisabledException) {
            //账号不可用
            result = new ResultInfo<>("error" , "账号不可用");
        } else if (e instanceof LockedException) {
            //账号锁定
            result = new ResultInfo<>("error" , "账号锁定");
        } else if (e instanceof InternalAuthenticationServiceException) {
            //用户不存在
            result = new ResultInfo<>("error" , "用户名不存在");
        }else{
            //其他错误
            result = new ResultInfo<>("error" , "用户名和密码格式错误");
        }
       //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
       //塞到HttpServletResponse中返回给前台
        httpServletResponse.getWriter().write(gson.toJson(result));
    }
}